package com.coai.twin.service

import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.kafka.annotation.KafkaListener
import org.springframework.stereotype.Service
import java.time.LocalDateTime

/**
 * 业务节点跟踪器 - 监听所有业务事件
 */
@Service
class BusinessNodeTracker(
    private val mongoTemplate: MongoTemplate,
    private val metricsCalculator: MetricsCalculator
) {
    
    @KafkaListener(topics = ["message-events", "file-events", "rtc-events", "warehouse-events", "logistics-events"])
    fun trackBusinessEvent(event: Map<String, Any>) {
        
        // 1. 保存原始事件
        val businessEvent = BusinessEvent(
            eventType = event["eventType"] as? String ?: "UNKNOWN",
            source = extractSource(event),
            data = event,
            timestamp = System.currentTimeMillis()
        )
        
        mongoTemplate.save(businessEvent, "business_events")
        
        // 2. 触发指标计算
        metricsCalculator.calculateMetrics(businessEvent)
    }
    
    private fun extractSource(event: Map<String, Any>): String {
        return when {
            event.containsKey("messageId") -> "message-service"
            event.containsKey("fileId") -> "file-service"
            event.containsKey("callId") -> "rtc-service"
            event.containsKey("orderId") -> "warehouse-service"
            else -> "unknown"
        }
    }
}

data class BusinessEvent(
    val eventType: String,
    val source: String,
    val data: Map<String, Any>,
    val timestamp: Long
)
